import type { VxeTableGridOptions } from '@vben/plugins/vxe-table';

import type { VbenFormSchema } from '#/adapter/form';
import type { OnActionClickFn } from '#/adapter/vxe-table';
import type { MachineryModel } from '#/api/equipment/models';
import type { LineModel } from '#/api/master/models';

import { getAllLineListApi, getLineListApi } from '#/api/master/line';

const _mapping: Record<number, number> = {};

/** 获取表格查询表单的字段配置。 */
export function useSearchSchema(): VbenFormSchema[] {
  return [
    {
      component: 'ApiSelect',
      componentProps: {
        allowClear: true,
        labelField: 'lineName',
        valueField: 'id',
        api: getLineListApi,
        immediate: false,
      },
      fieldName: 'lineId',
      label: '生产线',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
      fieldName: 'machineryCode',
      label: '设备编号',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
      fieldName: 'machineryName',
      label: '设备名称',
    },
  ];
}

/**
 * 获取编辑表单的字段配置。
 */
export function useSchema(): VbenFormSchema[] {
  return [
    {
      component: 'Input',
      fieldName: 'machineryCode',
      label: '设备编号',
      rules: 'required',
    },
    {
      component: 'Input',
      fieldName: 'machineryName',
      label: '设备名称',
      rules: 'required',
    },
    {
      component: 'Input',
      fieldName: 'brand',
      label: '品牌',
    },
    {
      component: 'Input',
      fieldName: 'model',
      label: '型号',
    },
    {
      component: 'Input',
      fieldName: 'spec',
      label: '规格',
      formItemClass: 'col-span-2 items-baseline',
    },
    {
      component: 'Input',
      fieldName: 'manufacturer',
      label: '制造商',
    },
    {
      component: 'DatePicker',
      componentProps: {
        valueFormat: 'YYYY-MM-DD',
      },
      fieldName: 'purchaseDate',
      label: '购置日期',
    },
    {
      component: 'ApiTreeSelect',
      componentProps: {
        allowClear: true,
        afterFetch: (data: LineModel[]) => {
          data.forEach((line) => {
            line.workstations?.forEach((workstation) => {
              _mapping[workstation.id] = line.id;
            });
          });
          return data.map((line) => ({
            value: line.id,
            label: line.lineName,
            selectable: false,
            children: line.workstations?.map((workstation) => ({
              value: workstation.id,
              label: workstation.wsCode,
              isLeaf: true,
            })),
          }));
        },
        api: getAllLineListApi,
      },
      dependencies: {
        trigger(values) {
          if (values.workstationId) {
            values.lineId = _mapping[values.workstationId]; // 设置产线 Id
          }
        },
        triggerFields: ['workstationId'],
      },
      fieldName: 'workstationId',
      label: '所在工位',
      rules: 'required',
    },
    {
      component: 'Input',
      fieldName: 'alias',
      label: '设备别名',
      help: '用于在自动点检等场合定位到具体的信号点，不需要时不用设置',
    },
    {
      component: 'Switch',
      componentProps: {
        checkedValue: 1,
        unCheckedValue: 0,
        checkedChildren: '启用',
        unCheckedChildren: '停用',
        class: 'w-auto',
      },
      fieldName: 'status',
      label: '状态',
      defaultValue: 1,
    },
    {
      component: 'Textarea',
      componentProps: {
        showCount: true,
        maxlength: 128,
      },
      fieldName: 'remark',
      label: '备注',
      formItemClass: 'col-span-2 items-baseline',
    },
  ];
}

/**
 * 获取表格列配置。
 * @param onActionClick 表格操作按钮点击事件
 */
export function useColumns(
  onActionClick?: OnActionClickFn<MachineryModel>,
): VxeTableGridOptions<MachineryModel>['columns'] {
  return [
    { type: 'seq', width: 60 },
    { field: 'machineryCode', title: '设备编号', width: 160 },
    { field: 'machineryName', title: '设备名称', width: 160 },
    { field: 'line.lineName', title: '产线', width: 140 },
    { field: 'workstation.wsCode', title: '工位', width: 100 },
    { field: 'brand', title: '品牌', width: 120 },
    { field: 'model', title: '型号', width: 120 },
    { field: 'spec', title: '规格', width: 140 },
    { field: 'manufacturer', title: '制造商', width: 120 },
    {
      field: 'status',
      title: '状态',
      width: 100,
      cellRender: { name: 'CellTag', attrs: { useStatus: true } },
    },
    { field: 'alias', title: '设备别名', minWidth: 100 },
    { field: 'remark', title: '备注', minWidth: 100 },
    { field: 'createdTime', title: '创建时间', width: 150 },
    {
      cellRender: {
        attrs: {
          nameField: 'machineryName',
          nameTitle: '设备',
          onClick: onActionClick,
        },
        name: 'CellOperation',
        options: [
          'edit', // 默认的编辑按钮
          'delete', // 默认的删除按钮
        ],
      },
      field: 'operation',
      fixed: 'right',
      title: '操作',
      width: 120,
    },
  ];
}
